﻿namespace Pibby.Core.IO
{
	using System;
	using System.IO;
	using System.Text;

	public static class FileNameSanitizer
	{
		public static string FixWebLink(string fileName)
		{
			StringBuilder builder = new StringBuilder(fileName);

			builder.Replace("%20", " ");

			string scrubbedName = builder.ToString();

			int pos = scrubbedName.IndexOf('?');

			if (pos > 0)
			{
				scrubbedName = scrubbedName.Substring(0, pos);
			}
			else
			{
				int equalPos = scrubbedName.IndexOf('=');

				if (equalPos > 0)
				{
					scrubbedName = scrubbedName.Substring(equalPos + 1);
				}
			}

			return scrubbedName;
		}

		public static string FixFileName(string fileName)
		{
			string scrubbedName = string.Empty;

			if (!string.IsNullOrEmpty(fileName))
			{
				scrubbedName = fileName;

				char[] invalidFileChars = Path.GetInvalidFileNameChars();

				foreach (char c in invalidFileChars)
				{
					scrubbedName = scrubbedName.Replace(c, ' ');
				}

				scrubbedName = scrubbedName.Replace("  ", " ");
			}
			
			return scrubbedName;
		}

		public static string ScrubSpaces(string fileName)
		{
			string scrubbedName = FixFileName(fileName);

			if (!string.IsNullOrEmpty(fileName))
			{
				scrubbedName = scrubbedName.Replace(" ", string.Empty);
			}

			return scrubbedName;
		}
		
        public static string CamelCaseName(string nonCamelCasedInput)
        {
			if (string.IsNullOrEmpty(nonCamelCasedInput))
			{
				throw new ArgumentNullException("nonCamelCasedInput"); // Resources.FilenameSanitizer_NullObjectError);
			}

            string[] separators = { " ", ".", "\t", System.Environment.NewLine, "!", "?" };
			
            string[] words = nonCamelCasedInput.Split(separators, StringSplitOptions.None);

			StringBuilder newName = new StringBuilder();

			int i = 0;
			foreach (string word in words)
			{
				if (i++ > 0)
				{
					newName.Append(" ");
				}

				if (!string.IsNullOrEmpty(word))
				{
					newName.AppendFormat(System.Globalization.CultureInfo.InvariantCulture, "{0}{1}", char.ToUpper(word[0]), word.Substring(1));
				}
			}

			return newName.ToString();
        }
	}
}
